package com.googlecode.dgwt.client.dijit.base.manager;

import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.ui.impl.FocusImpl;
import com.googlecode.dgwt.client.dijit.Widget;
import com.googlecode.dgwt.client.dojo.core.DOMElement;

/**
 * @author wellsantos@wellsantos.com
 * @since 0.01
 */
public class FocusManager {

    private static FocusManager manager;   
    
    protected FocusManager(){
        initializeEngine();
    }
        
    public static FocusManager get() {
        if (manager == null){
            manager = new FocusManager();
        }
        return manager;
    }
    
    protected FocusImpl getImpl() {
        return FocusImpl.getFocusImplForWidget();
    }

    public Element getFocusableElement(Widget widget){
        return widget.getAttachedElement("focusableElement");
    }
    
    public void onPostCreate(Widget widget){
        setTabIndex(widget, 0);
    }
    
    public int getTabIndex(Widget widget) {
        return getImpl().getTabIndex(getFocusableElement(widget).<DOMElement>cast());
    }

    public void setTabIndex(Widget widget, int index) {
        getImpl().setTabIndex(getFocusableElement(widget).<DOMElement>cast(), index);
    }

    public boolean isEnabled(Widget widget) {
        return !getFocusableElement(widget).getPropertyBoolean("disabled");
    }

    public void setEnabled(Widget widget, boolean enabled) {
        getFocusableElement(widget).setPropertyBoolean("disabled", !enabled);
    }
   
    public void setAccessKey(Widget widget, char key) {
        getFocusableElement(widget).setPropertyString("accessKey", "" + key);
    }

    public void setFocus(Widget widget, boolean focused) {
        if (focused) {
            getImpl().focus(getFocusableElement(widget).<DOMElement>cast());
        } else {
            getImpl().blur(getFocusableElement(widget).<DOMElement>cast());
        }
    }
    
    protected void initializeEngine() {
    }

}
